// 待办事项管理类
class TodoManager {
    constructor() {
        this.tasks = this.loadTasks();
        this.taskInput = document.getElementById('taskInput');
        this.addBtn = document.getElementById('addBtn');
        this.taskList = document.getElementById('taskList');
        this.taskCount = document.getElementById('taskCount');
        this.clearCompletedBtn = document.getElementById('clearCompleted');
        
        this.init();
    }

    // 初始化
    init() {
        this.renderTasks();
        this.bindEvents();
    }

    // 绑定事件
    bindEvents() {
        this.addBtn.addEventListener('click', () => this.addTask());
        this.taskInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addTask();
            }
        });
        this.clearCompletedBtn.addEventListener('click', () => this.clearCompleted());
    }

    // 从localStorage加载任务
    loadTasks() {
        const saved = localStorage.getItem('todoTasks');
        return saved ? JSON.parse(saved) : [];
    }

    // 保存任务到localStorage
    saveTasks() {
        localStorage.setItem('todoTasks', JSON.stringify(this.tasks));
    }

    // 添加任务
    addTask() {
        const text = this.taskInput.value.trim();
        if (!text) {
            alert('请输入任务内容！');
            return;
        }

        const task = {
            id: Date.now(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.tasks.unshift(task);
        this.saveTasks();
        this.renderTasks();
        this.taskInput.value = '';
        this.taskInput.focus();
    }

    // 删除任务
    deleteTask(id) {
        this.tasks = this.tasks.filter(task => task.id !== id);
        this.saveTasks();
        this.renderTasks();
    }

    // 切换任务完成状态
    toggleTask(id) {
        const task = this.tasks.find(task => task.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
        }
    }

    // 清除已完成任务
    clearCompleted() {
        this.tasks = this.tasks.filter(task => !task.completed);
        this.saveTasks();
        this.renderTasks();
    }

    // 渲染任务列表
    renderTasks() {
        if (this.tasks.length === 0) {
            this.taskList.innerHTML = `
                <div class="empty-state">
                    <i class="empty-icon">📋</i>
                    <p>暂无任务，请添加新任务</p>
                </div>
            `;
        } else {
            this.taskList.innerHTML = this.tasks.map(task => `
                <div class="task-item ${task.completed ? 'completed' : ''}">
                    <input 
                        type="checkbox" 
                        class="task-checkbox" 
                        ${task.completed ? 'checked' : ''}
                        onchange="todoManager.toggleTask(${task.id})"
                    >
                    <span class="task-text">${this.escapeHtml(task.text)}</span>
                    <button class="delete-btn" onclick="todoManager.deleteTask(${task.id})">删除</button>
                </div>
            `).join('');
        }

        this.updateTaskCount();
    }

    // 更新任务计数
    updateTaskCount() {
        const total = this.tasks.length;
        const completed = this.tasks.filter(task => task.completed).length;
        const remaining = total - completed;
        
        this.taskCount.textContent = `共 ${total} 个任务，已完成 ${completed} 个，剩余 ${remaining} 个`;
        
        // 显示/隐藏清除已完成按钮
        this.clearCompletedBtn.style.display = completed > 0 ? 'block' : 'none';
    }

    // HTML转义，防止XSS
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 初始化应用
const todoManager = new TodoManager();

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    todoManager.taskInput.focus();
});
